from celery import shared_task
from django.utils import timezone
from datetime import timedelta

from django.core.mail import send_mail

from bookApp.models import BookLoan


@shared_task
def send_due_date_reminders():
    today = timezone.now().date()
    due_soon = today + timedelta(days=7)
    loans = BookLoan.objects.filter(due_date=due_soon, returned_date=None)

    for loan in loans:
        send_mail(
            'Library Book Due Soon',
            f'Dear {loan.borrower.username},\n\nYour book "{loan.book.title}" is due in 7 days. Please return it soon.',
            'library@example.com',
            [loan.borrower.email],
            fail_silently=False,
        )
